package com.google.code.mochaccino.framework.transaction;
/*
 * Copyright 2012 Claude Houle claude.houle@gmail.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import com.google.code.mochaccino.framework.transaction.exception.TransactionManagementException;
import com.google.common.base.Preconditions;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

/** Aspect for declarative transaction management */
@Aspect
public class TransactionAspect {

	private static TransactionManager manager = null;

	/** Return true if started. */
	public static final boolean isStarted() {
		return manager.isStarted();
	}

	/** Set the transaction manager */
	public static final void setTransactionManager( TransactionManager manager ) {
		TransactionAspect.manager = manager;
	}

	/** Around the transaction */
	@Around( value = "transactional(txCtx)" )
	public Object around( ProceedingJoinPoint jp, Transactional txCtx ) throws Throwable {
		Propagation propagation = txCtx.propagation();
		return manager.handle( propagation, jp );
	}

	/** The Pointcut */
	@Pointcut( argNames = "txCtx", value = "execution(* *(..) throws *) && @annotation(txCtx)" )
	void transactional( Transactional txCtx ) {
	}

	public static void registerListener( TransactionListener listener ) throws TransactionManagementException {
		Preconditions.checkNotNull( manager, "Not transaction manager facade." );
		Preconditions.checkNotNull( listener, "Listener cannot be null!" );
		manager.registerListener( listener );
	}
}